package cn.gjculture.shopping.api.service.impl;

import cn.gjculture.shopping.api.dao.CommonDeleteMapper;
import cn.gjculture.shopping.api.dao.CommonUpdateMapper;
import cn.gjculture.shopping.api.dao.UserDao;
import cn.gjculture.shopping.api.entity.Token;
import cn.gjculture.shopping.api.entity.User;
import cn.gjculture.shopping.api.service.TokenService;
import cn.gjculture.shopping.api.service.UserService;
import cn.gjculture.shopping.api.util.DateUtil;
import cn.gjculture.shopping.api.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;

    @Autowired
    TokenService tokenService;

    @Autowired
    CommonUpdateMapper commonUpdateMapper;

    @Autowired
    CommonDeleteMapper commonDeleteMapper;

    @Override
    public int insert(User user) {
        user.setUserId(UUIDUtil.getUUID());
        user.setInsertTime(DateUtil.getTimestamp());
        user.setUpdateTime(DateUtil.getTimestamp());
        return userDao.insert(user);
    }

    @Override
    public int update(User user) {
        user.setUpdateTime(DateUtil.getTimestamp());
        return commonUpdateMapper.updateUser(user);
    }

    @Override
    public List<User> query() {
        return userDao.query();
    }

    @Override
    public User queryById(String userId) {
        return userDao.queryById(userId);
    }

    @Override
    public int delete(List<String> userIds) {
        return commonDeleteMapper.deleteUser(userIds);
    }

    @Override
    public User queryByName(String name) {
        return userDao.queryByName(name);
    }

    @Override
    public boolean updatePassword(String tokenId, String oldPassword, String newPassword) {
        Token token=tokenService.queryByToken(tokenId);
        if(token==null || StringUtils.isEmpty(token.getCustomerId())) return false;
        User user=userDao.queryById(token.getCustomerId());
        if(user==null|| StringUtils.isEmpty(user.getPassword())) return false;
        if(user.getPassword().equals(oldPassword)){
            user.setPassword(newPassword);
            userDao.updatePassword(user);
            return true;
        }
        return false;
    }
}
